package com.base.cn.platform.os.controller.order.order;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.file.FileDownloadUtil;
import com.base.cn.platform.os.common.utils.order.*;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.controller.order.order.utils.OrderExportExcelUtils;
import com.base.cn.platform.os.entity.order.order.Order;
import com.base.cn.platform.os.entity.order.order.OrderBook;
import com.base.cn.platform.os.entity.order.order.OrderCondition;
import com.base.cn.platform.os.entity.order.order.OrderType;
import com.base.cn.platform.os.entity.order.shop.ShopData;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.qa.qaattend.QaAttendService;
import com.base.cn.platform.os.service.exam.record.ExamBuyRecordService;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.op.activity.OpActivityBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponCodeBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponShopBiz;
import com.base.cn.platform.os.service.order.check.CreateOrderDataFrom;
import com.base.cn.platform.os.service.order.check.OrderCheckHandle;
import com.base.cn.platform.os.service.order.init.ShopDataInit;
import com.base.cn.platform.os.service.order.order.OrderBiz;
import com.base.cn.platform.os.service.order.order.OrderBookBiz;
import com.base.cn.platform.os.service.order.price.OrderPrice;
import com.base.cn.platform.os.service.order.price.OrderPriceHandle;
import com.base.cn.platform.os.service.user.member.CusUserMemberBuyRecordBiz;
import com.github.pagehelper.PageInfo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Controller接口
 *
 * @author s.li
 * @create 2018-05-08-13:52
 */
@RestController
@RequestMapping("/manage/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderBiz orderBiz;
    @Autowired
    private OrderBookBiz orderBookBiz;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private ExamBuyRecordService examBuyRecordService;
    @Autowired
    private OpActivityBiz opActivityBiz;
    @Autowired
    private OpCouponShopBiz opCouponShopBiz;
    @Autowired
    private OpCouponCodeBiz opCouponCodeBiz;
    @Autowired
    private CusUserMemberBuyRecordBiz cusUserMemberBuyRecordBiz;
    @Autowired
    private SysConfigBiz sysConfigBiz;
    @Autowired
    private ShopDataInit shopDataInit;
    @Autowired
    private QaAttendService qaAttendService;

    /**
     * 通过订单号，查询订单对数
     * @param orderNo 订单号
     * @return  Order 订单对象
     */
    @RequestMapping("/findOrderBuyNo")
    public Order findOrderBuyNo(@RequestParam("orderNo") String orderNo){
        return orderBiz.findOne("orderNo='"+orderNo+"'",null);
    }

    /**
     * 通过ID，查询订单详情
     * @param orderCondition 查询条件
     * @return Order订单对象
     */
    @RequestMapping("/findOrderInfo")
    public Order findOrderInfo(@RequestBody OrderCondition orderCondition){
        return orderBiz.findOrderInfo(orderCondition);
    }

    /**
     * 分页查询订单数据列表
     * @param condition 查询条件
     * @param currentPage 页码
     * @param pageSize 页面显示大小
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据
     * @return PageInfo<Order>
     */
    @RequestMapping("/findWebOrderPage")
    public PageInfo<Order> findWebOrderPage(@RequestBody OrderCondition condition,
                                            @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                            @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize,
                                            @RequestParam("setUserData") boolean setUserData,
                                            @RequestParam("setDetailsData") boolean setDetailsData,
                                            @RequestParam("setShopData") boolean setShopData,
                                            @RequestParam("setOrderBook") boolean setOrderBook){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return  orderBiz.findOrderPage(condition,page,setUserData,setDetailsData,setShopData,setOrderBook);
    }

    /**
     * 分页查询订单数据列表
     * @param condition 查询条件
     * @param currentPage 页码
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据
     * @return PageInfo<Order>
     */
    @RequestMapping("/findOrderPage")
    public PageInfo<Order> findOrderPage(@RequestBody OrderCondition condition,
                                         @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                         @RequestParam("setUserData") boolean setUserData,
                                         @RequestParam("setDetailsData") boolean setDetailsData,
                                         @RequestParam("setShopData") boolean setShopData,
                                         @RequestParam("setOrderBook") boolean setOrderBook){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        return  orderBiz.findOrderPage(condition,page,setUserData,setDetailsData,setShopData,setOrderBook);
    }

    /**
     * 查询订单数据列表(不分页)
     * @param condition 查询条件
     * @param setUserData 是否设置用户数据
     * @param setDetailsData 是否设置流水数据
     * @param setShopData 是否设置商品数据
     * @return List<Order>
     */
    @RequestMapping("/findOrderList")
    public List<Order> findOrderList(@RequestBody OrderCondition condition,
                                     @RequestParam("setUserData") boolean setUserData,
                                     @RequestParam("setDetailsData") boolean setDetailsData,
                                     @RequestParam("setShopData") boolean setShopData,
                                     @RequestParam("setOrderBook") boolean setOrderBook){
        return orderBiz.findOrderList(condition, setUserData, setDetailsData, setShopData, setOrderBook);
    }

    /**
     * 修改订单状态
     * @param sysUserId 管理员ID
     * @param orderId 订单ID
     * @param orderStatus 订单状态
     * @param payTime 支付时间
     * @param payType 支付类型
     * @param externalOrderNo 第三方支付流水号
     * @param mailName 物流公司
     * @param mailCode 物流单号
     * @param mailTime 发货时间
     * @return Map<String,Object>
     */
    @RequestMapping("/updateOrderStatus")
    public Map<String,Object> updateOrderStatus(@RequestParam("sysUserId") BigDecimal sysUserId,
                                                @RequestParam("orderId") BigDecimal orderId,
                                                @RequestParam("orderStatus") String orderStatus,
                                                @RequestParam(value = "payTime",required = false) String payTime,
                                                @RequestParam(value = "payType",required = false) String payType,
                                                @RequestParam(value = "externalOrderNo",required = false) String externalOrderNo,
                                                @RequestParam(value = "mailName",required = false) String mailName,
                                                @RequestParam(value = "mailCode",required = false) String mailCode,
                                                @RequestParam(value = "mailTime",required = false) String mailTime) throws Exception{
        Order order = orderBiz.findById(orderId);
        if(order.getOrderStatus().equals(orderStatus)){
            return ResultUtil.ERROR("订单状态错误，操作失败");
        }
        if(orderStatus.equals(OrderStatus.REFUND) && !order.getOrderStatus().equals(OrderStatus.SUCCESS)){
            return ResultUtil.ERROR("该订单未支付，不可退费");
        }
        if(orderStatus.equals(OrderStatus.CANCEL) && order.getOrderStatus().equals(OrderStatus.SUCCESS)){
            return ResultUtil.ERROR("该订单已支付成功，不可取消");
        }
        if(orderStatus.equals(OrderStatus.SENDOUT)){
            if(!order.getOrderStatus().equals(OrderStatus.SUCCESS)){
                return ResultUtil.ERROR("订单状态错误，发货失败");
            }
        }
        if(orderStatus.equals(OrderStatus.REFUND)){//退费
            //试卷、问答、充值、旁听不可以退费
            if(order.getSellTypeList().contains(ShopType.ORDER_SHOP_EXAM)
                    || order.getSellTypeList().contains(ShopType.ORDER_SHOP_ACCOUNT)
                    || order.getSellTypeList().contains(ShopType.ORDER_SHOP_ATTEND)){
                return ResultUtil.ERROR("订单包含不可退费商品");
            }
        }
        boolean status = true;
        if(orderStatus.equals(OrderStatus.SUCCESS)){
            if(StringUtils.isEmpty(payType)){
                return ResultUtil.ERROR("请选择支付类型");
            }
            order.setPayType(payType);
            if(StringUtils.isEmpty(payTime)){
                return ResultUtil.ERROR("请填写支付时间");
            }
            if(StringUtils.isEmpty(externalOrderNo)){
                return ResultUtil.ERROR("请填写第三方订单流水号");
            }
            if(order.getOrderStatus().equals(orderStatus)){
                return ResultUtil.ERROR("该订单已审核过");
            }
            //验证订单数据
            Map<String,Object> resultMap = this.checkAgainOrderShopData(order);
            if(!ResultUtil.getSuccess(resultMap)){
                return resultMap;
            }
            status = false;
        }
        if(status){
            order = orderBiz.setOrderExData(order,false,true,true,false);
        }
        if(payTime==null && orderStatus.equals(OrderStatus.SUCCESS)){
            //设置支付时间
            order.setPayTime(new Date());
        }else{
            if(StringUtils.isNotEmpty(payTime)){
                try {
                    order.setPayTime(DateUtils.parseDate(payTime,new String[]{"yyyy-MM-dd HH:mm:ss"}));
                } catch (ParseException e) {
                    logger.error("设置支付时间错误");
                }
            }
        }
        order.setPayType(payType);
        order.setExternalOrderNo(externalOrderNo);
        order.setOrderStatus(orderStatus);
        if(orderStatus.equals(OrderStatus.SENDOUT)){//发货
            OrderBook orderBook = new OrderBook();
            orderBook.setMailName(mailName);
            orderBook.setMailCode(mailCode);
            if(StringUtils.isEmpty(mailName)){
                return ResultUtil.ERROR("请填写物流公司名");
            }
            if(StringUtils.isEmpty(mailCode)){
                return ResultUtil.ERROR("请填写物流单号");
            }
            if(StringUtils.isEmpty(mailTime)){
                return ResultUtil.ERROR("请选择发货时间");
            }
            try {
                orderBook.setMailTime(DateUtils.parseDate(mailTime,new String[]{"yyyy-MM-dd HH:mm:ss"}));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            orderBook.setMailStatus(1);
            orderBook.setOrderId(order.getId());
            orderBookBiz.sendOutOrder(orderBook);
        }else{//修改订单状态
            orderBiz.updateOrderStatus(order,sysUserId);
            if((orderStatus.equals(OrderStatus.CANCEL) || orderStatus.equals(OrderStatus.REFUND)) && order.getSellTypeList().contains(ShopType.ORDER_SHOP_COURSE)){
                if(DataUtil.idIsNotNull(order.getCouponCodeId())){
                    opCouponCodeBiz.updateCouponCodeStatus(order.getCouponCodeId(),1);
                }
                courseBuyRecordService.updateRecordCourseStatus(order.getId(),order.getOrderStatus());
            }
        }
        return ResultUtil.SUCCESS("操作成功",order);
    }

    /**
     * 删除订单
     * @param orderIds
     * @param userId
     * @return
     */
    @RequestMapping("/deleteOrder")
    public Map<String,Object> deleteOrder(@RequestParam("orderIds") String orderIds,@RequestParam("userId") BigDecimal userId){
        orderBiz.deleteOrder(orderIds,userId);
        return ResultUtil.SUCCESS();
    }

    /**
     * 前台验证订单是否能购买（支付前重新验证商品合法性）
     * @param userId 用户ID
     * @param orderNo 订单号
     * @param orderType 订单类型
     * @param payType 支付类型
     * @param price 充值金额
     * @return Map<String,Object>
     */
    @RequestMapping("/checkWebOrderData")
    public Map<String,Object> checkWebOrderData(@RequestParam("userId") BigDecimal userId,
                                                @RequestParam("orderNo") String orderNo,
                                                @RequestParam("orderType") String orderType,
                                                @RequestParam("payType") String payType,
                                                @RequestParam(value = "price",required = false,defaultValue = "0") double price){

        TreeMap<String,String> onOffConfig = sysConfigBiz.getSysConfigContext(ConfigName.ONOFF);
        String paySwitch = onOffConfig.get("paySwitch");
        if(!"ON".equals(paySwitch)){
            return ResultUtil.ERROR("支付入口已关闭，支付失败");
        }
        Order order = orderBiz.findOrderByOrderNo(orderNo,false,true,true,false);;
        if(orderType.equals(OrderType.COMMON.getKey())){
            if(order==null){
                return ResultUtil.ERROR("订单不存在");
            }
            if(order.getOrderStatus().equals(OrderStatus.SUCCESS)){
                return ResultUtil.ERROR("订单已支付成功，不需重新支付");
            }
            if(!order.getOrderStatus().equals(OrderStatus.INIT)){
                return ResultUtil.ERROR("订单状态异常，支付失败");
            }
            order.setActivityId(null);
        }else if(orderType.equals(OrderType.ACCOUNT.getKey())){
            if(order!=null){
                return ResultUtil.SUCCESS("充值订单已支付成功",order);
            }
            order = new Order();
            order.setUserId(userId);
            order.setSumPrice(price);
            order.setRealPrice(price);
            order.setOrderType(orderType);
            order.setOrderNo(orderNo);
            order.setShopNames("账户充值");
        }
        order.setPayType(payType);
        //验证订单
        Map<String,Object> resultMap = this.checkAgainOrderShopData(order);
        if(ResultUtil.getSuccess(resultMap)){
            ResultUtil.setEntity(resultMap,order);
        }
        return resultMap;
    }

    @RequestMapping("/downloadExcelOrdersList")
    public ResponseEntity<byte[]> downloadExcelOrdersList(@RequestBody OrderCondition condition, @RequestParam("pageSize") int pageSize ) throws Exception{

        return  exportOrderXls(condition,pageSize);
    }

    /**
     * 通过ID，查询订单详情
     * @param orderCondition 查询条件
     * @return Order订单对象
     */
    @RequestMapping("/orderInfoActivity")
    public Map<String,List> orderInfoActivity(@RequestBody OrderCondition orderCondition){
        return orderBiz.orderInfoActivity(orderCondition);
    }

    /**
     * 导出订单数据列表
     * @param condition 查询条件
     * @param pageSize 数据数量
     */
    private ResponseEntity<byte[]> exportOrderXls(OrderCondition condition, int pageSize) throws Exception {
        //表格头部
        String [] heads = new String[] {"ID","订单号", "订单类型", "购买商品","商品类型", "购买用户","手机号", "下单时间", "支付时间", "支付类型","支付状态","订单总金额", "实际支付金额","活动减额","优惠减额", "运费金额","第三方订单号","订单来源", "推广订单（是/否）","推广员分成金额","推广奖励金额"};
        //生成文件的容器
        List<Map<String,Object>> srcFile = new ArrayList<>();
        //文件名
        String expName = "订单数据"+System.currentTimeMillis();
        //获取数据
        PageInfo<Order> webOrderPage = this.findWebOrderPage(condition, 1, pageSize, true, false, false, false);
        if(ObjectUtils.isNotEmpty(webOrderPage.getList())){
            //每2000数据一个execl，如果页数大于1循环生成
            if(webOrderPage.getPages()>=1){
                for(int i=1;i<=webOrderPage.getPages();i++){
                    if(i>1){
                        webOrderPage =   this.findWebOrderPage(condition,i,pageSize,true,false,false,false);
                    }
                    OrderExportExcelUtils.generateFile(getData(webOrderPage.getList()),heads,expName+"_"+i+".xls",srcFile);
                }
            }
        }
        return FileDownloadUtil.createRar(srcFile,expName);
    }

    /**
     *
     * @param orderList 列表数据
     * @return
     */
    private List<List<String>> getData( List<Order> orderList){
        List<List<String>> data = new ArrayList<>();

        orderList.forEach((v)->{
            CusUser user =v.getUser();
            //商品类型集
            StringBuilder sellTypeList =new StringBuilder();
            String[] sellTypeLists = v.getSellTypeList().toString().split(",");
            for(String sellType:sellTypeLists){
                switch (sellType){
                    case "COURSE":
                        sellTypeList.append("课程 ");
                        break;
                    case "BOOK":
                        sellTypeList.append("图书 ");
                        break;
                    case "MEMBER":
                        sellTypeList.append("会员 ");
                        break;
                    case "ACCOUNT":
                        sellTypeList.append("充值");
                        break;
                    case "EXAM":
                        sellTypeList.append("试卷 ");
                        break;
                    case "QA":
                        sellTypeList.append("问答 ");
                        break;
                    case "ATTEND":
                        sellTypeList.append("旁听");
                        break;
                }
            }
            //推广订单（是/否）
            String spread ="";
            if(ObjectUtils.isNotEmpty(v.getSpread())){
                switch (v.getSpread()){
                    case 0:
                        spread="否";
                        break;
                    case 1:
                        spread="是";
                        break;
                }
            }

            data.add(Arrays.asList(
                    v.getId().toString(),
                    v.getOrderNo(),
                    OrderExportExcelUtils.backOrderType(v.getOrderType()),
                    v.getShopNames(),
                    sellTypeList.toString(),
                    ObjectUtils.isNotEmpty(user)?user.getNickname() + " " + user.getMobile() +"(" + user.getId() + ")":"",
                    ObjectUtils.isNotEmpty(user)?user.getMobile():"",
                    DateUtils.format(v.getCreateTime()),
                    ObjectUtils.isNotEmpty(v.getPayTime())?DateUtils.format(v.getPayTime()):"",
                    OrderExportExcelUtils.backPaymentType(v.getPayType()),
                    OrderExportExcelUtils.backOrderStatus(v.getOrderStatus()),
                    v.getSumPrice().toString(),
                    v.getRealPrice().toString(),
                    v.getActivityPrice().toString(),
                    v.getYhPrice().toString(),
                    v.getFreightPrice().toString(),
                    ObjectUtils.isNotEmpty(v.getExternalOrderNo())?v.getExternalOrderNo():"",
                    ObjectUtils.isNotEmpty(v.getOrderForm())?OrderExportExcelUtils.backOrderFrom(v.getOrderForm()):"",
                    spread,
                    v.getSpreadPrice().toString(),
                    v.getBonusPrice().toString()
            ));

        });
        return  data;
    }

    //=========================================以下是新的代码，与当前功能无关================

    /**
     * 创建赠送商品订单接口
     * @return Map<String,Object>
     */
    @RequestMapping("/createFreeOrder")
    public Map<String,Object> createFreeOrder(@RequestParam("userId") BigDecimal userId,
                                              @RequestParam("shopData") String shopData){
        if(!DataUtil.idIsNotNull(userId)){
            return ResultUtil.ERROR("未指定学员");
        }
        CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
        createOrderDataFrom.setShopData(shopData);
        createOrderDataFrom.setUserId(userId);
        createOrderDataFrom.setPayType(PayType.PAY_TYPE_ADMIN_FREE);
        createOrderDataFrom.setOrderForm(OrderSource.ORDER_FORM_ADMIN);
        //创建免费订单
        Map<String,Object> resultMap  = this.createFreeOrder(createOrderDataFrom);
        if(ResultUtil.getSuccess(resultMap)){
            ResultUtil.setMessage(resultMap,"赠送成功");
        }
        return resultMap;
    }

    /**
     * 前台生成免费订单
     * @param createOrderDataFrom 创建订单的数据
     * @return Map<String,Object>
     */
    @RequestMapping("/createWebFreeOrder")
    public Map<String,Object> createWebFreeOrder(@RequestBody CreateOrderDataFrom createOrderDataFrom) throws Exception{
        String payType = createOrderDataFrom.getPayType();
        if(!PayType.PAY_TYPE_MEMBER.equals(payType) && !PayType.PAY_TYPE_FREE.equals(payType)){
            return ResultUtil.ERROR("数据错误，生成失败");
        }
        //创建免费订单
        Map<String,Object> resultMap  = this.createFreeOrder(createOrderDataFrom);
        if(ResultUtil.getSuccess(resultMap)){
            ResultUtil.setMessage(resultMap,"报名成功");
        }
        return resultMap;
    }

    /**
     * 创建免费订单
     * @param createOrderDataFrom
     * @return Map<String,Object>
     */
    private Map<String,Object> createFreeOrder(CreateOrderDataFrom createOrderDataFrom){
        createOrderDataFrom.setPay(false);
        createOrderDataFrom.setSubmit(true);
        createOrderDataFrom.setFree(true);
        createOrderDataFrom.setOrderType(OrderType.COMMON.getKey());
        //验证订单数据
        Map<String,Object> resultMap = this.checkCreateOrderData(createOrderDataFrom);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        Order order = null;
        try {
            order = orderBiz.createOrder(createOrderDataFrom);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.SUCCESS(order);
    }

    /**
     * 获取支付订单的商品列表
     * @param createOrderDataFrom 创建订单数据
     * @return Map<String,Object>
     */
    @RequestMapping("/getPayOrderShopList")
    public Map<String,Object> getPayOrderShopList(@RequestBody CreateOrderDataFrom createOrderDataFrom){
        //设置为是支付订单（非赠送、免费订单）
        createOrderDataFrom.setPay(true);
        //验证订单数据
        Map<String,Object> resultMap = this.checkCreateOrderData(createOrderDataFrom);
        OrderPriceHandle.sysConfigBiz =sysConfigBiz;
        OrderPrice orderPrice = OrderPriceHandle.getOrderPrice(createOrderDataFrom);
        CreateOrderDataFrom entity = (CreateOrderDataFrom) ResultUtil.getEntity(resultMap);
        if(ObjectUtils.isNotEmpty(entity)){
            entity.setOrderPrice(orderPrice);
            Map<String,List<ShopData>> shopDataListMap = createOrderDataFrom.getShopList().stream().collect(Collectors.groupingBy(e->e.getShopType()));
            List<ShopData> bookShopList = shopDataListMap.get(ShopType.ORDER_SHOP_BOOK);
            if(ObjectUtils.isNotEmpty(bookShopList)){
                entity.setHaveBook(true);
            }
        }
        return resultMap;
    }

    /**
     * 创建支付订单接口
     * @param orderDataFrom 创建订单数据对象
     * @return Map<String,Object>
     */
    @RequestMapping("/createPayOrder")
    public Map<String,Object> createPayOrder(@RequestBody CreateOrderDataFrom orderDataFrom){
        //获取支付开关
        TreeMap<String,String> onOffConfig = sysConfigBiz.getSysConfigContext(ConfigName.ONOFF);
        String paySwitch = onOffConfig.get("paySwitch");
        if(!"ON".equals(paySwitch)){
            return ResultUtil.ERROR("支付入口已关闭，创建订单失败");
        }
        //设置为是支付订单（非赠送、免费订单）
        orderDataFrom.setPay(true);
        //确认提交订单数据
        orderDataFrom.setSubmit(true);
        //验证订单数据
        Map<String,Object> resultMap = this.checkCreateOrderData(orderDataFrom);
        //验证不通过直接返回
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //创建订单数据
        Order order;
        //创建普通订单
        if(orderDataFrom.getOrderType().equals(OrderType.COMMON.getKey())){
            try {
                order = orderBiz.createOrder(orderDataFrom);
            } catch (Exception e) {
                logger.error("createPayOrder()-->{}",e);
                return ResultUtil.ERROR("系统错误，创建订单失败");
            }
            return ResultUtil.SUCCESS("订单创建成功",order);
        }else if(orderDataFrom.getOrderType().equals(OrderType.ACCOUNT.getKey())){//创建充值临时订单
            String orderNo = GenerateOrderNum.getInstance().generateOrderNo();
            order = new Order();
            order.setOrderNo(orderNo);
            double realPrice = orderDataFrom.getShopList().stream().mapToDouble(e->e.getRealPrice()).sum();
            order.setSumPrice(realPrice);
            order.setRealPrice(realPrice);
            order.setOrderStatus(OrderStatus.INIT);
            return ResultUtil.SUCCESS("充值订单设置成功",order);
        }
        return null;
    }


    /**
     * 检测订单中的商品数据
     * @param order 订单对象
     * @return  Map<String,Object>
     */
    private Map<String,Object> checkAgainOrderShopData(Order order){
        CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
        createOrderDataFrom.setUserId(order.getUserId());
        createOrderDataFrom.setOrderType(order.getOrderType());
        createOrderDataFrom.setPayType(order.getPayType());
        createOrderDataFrom.setSubmit(true);
        createOrderDataFrom.setPay(true);
        createOrderDataFrom.setCheckAgain(true);//重新做第二次认证
        String shopData;
        if(order.getOrderType().equals(OrderType.COMMON.getKey())){
            orderBiz.setOrderExData(order,false,true,false,false);
            shopData = order.getOrderDetailsList().stream().map(e->e.getShopId()+"-"+e.getShopType()+"-"+e.getBuyNum()).collect(Collectors.joining(","));
        }else{
            shopData = "0-ACCOUNT-"+order.getRealPrice();
        }
        createOrderDataFrom.setOrder(order);
        createOrderDataFrom.setShopData(shopData);
        //验证
        return this.checkCreateOrderData(createOrderDataFrom);
    }

    /**
     * 验证创建订单的数据
     * @param createOrderDataFrom
     * @return Map<String,Object>
     */
    private Map<String,Object> checkCreateOrderData(CreateOrderDataFrom createOrderDataFrom){
        //初始化工具类、服务接口类
        OrderCheckHandle.courseBuyRecordService = courseBuyRecordService;
        OrderCheckHandle.examBuyRecordService = examBuyRecordService;
        OrderCheckHandle.opCouponCodeBiz = opCouponCodeBiz;
        OrderCheckHandle.opActivityBiz = opActivityBiz;
        OrderCheckHandle.opCouponShopBiz = opCouponShopBiz;
        OrderCheckHandle.cusUserMemberBuyRecordBiz = cusUserMemberBuyRecordBiz;
        OrderCheckHandle.sysConfigBiz = sysConfigBiz;
        OrderCheckHandle.qaAttendService = qaAttendService;
        //初始化商品数据
        shopDataInit.initShopData(createOrderDataFrom);

        //验证订单数据
        Map<String,Object> resultMap = OrderCheckHandle.orderCheck(createOrderDataFrom);
        return resultMap;
    }

    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @RequestMapping("/cancelOrder")
    public Map<String,Object> cancelOrder(@RequestParam("orderId") BigDecimal orderId) throws Exception {
        return updateOrderStatus(new BigDecimal(0),orderId,"CANCEL",null,null,null,null,null,null);
    }


    /**
     * 积分兑换商品
     * @return Map<String,Object>
     */
    @RequestMapping("/exchangeFreeOrder")
    public Map<String,Object> exchangeFreeOrder(@RequestParam("userId") BigDecimal userId,
                                                @RequestParam("shopData") String shopData){
        if(!DataUtil.idIsNotNull(userId)){
            return ResultUtil.ERROR("未指定学员");
        }
        CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
        createOrderDataFrom.setShopData(shopData);
        createOrderDataFrom.setUserId(userId);
        createOrderDataFrom.setPayType(PayType.PAY_TYPE_ADMIN_INTEGRAL);
        createOrderDataFrom.setOrderForm(OrderSource.ORDER_FORM_INTEGRAL);
        //创建免费订单
        Map<String,Object> resultMap  = this.createFreeOrder(createOrderDataFrom);
        if(ResultUtil.getSuccess(resultMap)){
            ResultUtil.setMessage(resultMap,"兑换成功");
        }
        return resultMap;
    }
}
